package tuwien.similaritymeasurement;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;

public class ImageAnalyzer {

	private Bitmap bitmap;
	private int[][] bmpColors;
	
	private int numFilRegions = 3;
	private int sampleSize = 30;
	int imageWidth;
	int imageHeight;
	
	public ImageAnalyzer(Bitmap b){
		bitmap = b;
		bmpColors = calculateColors(b);
	}

	public double calcDistance(Bitmap b){

		int[][] image2 = calculateColors(b);
		double dist = 0;

		for (int x = 0; x < numFilRegions; x++)
			for (int y = 0; y < numFilRegions; y++){
				int r1 = Color.red(bmpColors[x][y]);
				int g1 = Color.green(bmpColors[x][y]);
				int b1 = Color.blue(bmpColors[x][y]);
				int r2 = Color.red(image2[x][y]);
				int g2 = Color.green(image2[x][y]);
				int b2 = Color.blue(image2[x][y]);
				double tempDist = Math.sqrt((r1 - r2) * (r1 - r2) + (g1 - g2)
						* (g1 - g2) + (b1 - b2) * (b1 - b2));
				dist += tempDist;
			}
		return dist;
	}


	public int[][] calculateColors(Bitmap b){

		imageHeight = b.getHeight();
		imageWidth = b.getWidth();

		int[][] avgColors = new int[numFilRegions][numFilRegions];

		int distanceX = imageWidth/numFilRegions;
		int distanceY = imageHeight/numFilRegions;

		int startPosX = distanceX/2 - (sampleSize);
		int startPosY = distanceY/2 - (sampleSize);

		for (int i = 0; i < numFilRegions; i++) {
			for (int j = 0; j < numFilRegions; j++) {
				avgColors[j][i]=calculateSingleColor(b,startPosX+j*distanceX,startPosY+i*distanceY);
			}
		}

		return avgColors;

	}

	public int calculateSingleColor(Bitmap b, int startPosX, int startPosY){

		//Log.i("test", startPosX + ", " + startPosY);

		double[] channel = new double[3];
		for (int y = startPosY; y < startPosY+sampleSize; y++) {
			for (int x = startPosX; x < startPosX+sampleSize; x++) {
				//Log.i("test","Cur.pixel - X:"+ x +" ,Y:" + y);
				int pixel = b.getPixel(x,y);
				channel[0] += Color.red(pixel);
				channel[1] += Color.blue(pixel);
				channel[2] += Color.green(pixel);
			}
		}
		int window = sampleSize*sampleSize;
		channel[0] /= window;
		channel[1] /= window;
		channel[2] /= window;

		int c = Color.rgb((int)channel[0], (int)channel[0], (int)channel[0]);

		//Log.i("test", "Color produced: "+c);

		return c;
	}

	public Bitmap getBitmap() {
		return bitmap;
	}

	public void setBitmap(Bitmap bitmap) {
		this.bitmap = bitmap;
	}

}
